package server

import (
	"github.com/streadway/amqp"
	"log"
)

func failOnError(err error, msg string) {
	if err != nil {
		log.Fatalf("%s: %s", msg, err)
	}
}

type SendRabbitMQ struct {
	conn *amqp.Connection //连接
	ch   *amqp.Channel    //频道
	q    amqp.Queue       //队列

}

func NewSendRabbitMQ(url string, queuename string) *SendRabbitMQ {
	mysend := new(SendRabbitMQ)
	var err error
	mysend.conn, err = amqp.Dial(url)
	failOnError(err, "Failed to connect to RabbitMQ")

	mysend.ch, err = mysend.conn.Channel()
	failOnError(err, "Failed to open a channel")

	mysend.q, err = mysend.ch.QueueDeclare(
		queuename, // name
		true,      // durable
		false,     // delete when unused
		false,     // exclusive
		false,     // no-wait
		nil,       // arguments
	)
	failOnError(err, "Failed to declare a queue")
	return mysend
}
func (sr *SendRabbitMQ) SendData(Data string) {
	var err error
	err = sr.ch.Publish(
		"",        // exchange
		sr.q.Name, // routing key
		false,     // mandatory
		false,
		amqp.Publishing{
			DeliveryMode: amqp.Persistent,
			ContentType:  "text/plain",
			Body:         []byte(Data),
		})
	failOnError(err, "Failed to publish a message")
	log.Printf(" [x] Sent %s", Data)
}
func (sr *SendRabbitMQ) Close() {
	sr.ch.Close()
	sr.conn.Close()
}
